<template>
  <view>
    <button @click="chooseImage">选择图片</button>
    <button @click="recognizeImage" :disabled="!selectedImage">识别图片</button>
    <image :src="imageUrl" mode="widthFix" v-if="imageUrl" />
    <view v-if="animalInfo">
      <text>识别结果:</text>
      <view>
        <text>名称: {{ animalInfo.name }}</text>
        <text>置信度: {{ animalInfo.score }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedImage: null,
      imageUrl: '',
      animalInfo: null,
      apiConfig: {
        APP_ID: '42416784',
        API_KEY: '9ws9b5BQtgGZn9WGjUwEG8Ej',
        SECRET_KEY: 'vbVCoIm9UfWO5N0mrxynOcLC5UTCwP6q'
      },
      accessToken: null,
    };
  },
  methods: {
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          this.imageUrl = res.tempFilePaths[0];
          this.selectedImage = res.tempFiles[0];
        }
      });
    },
    recognizeImage() {
		
      if (!this.selectedImage) {
        return;
      }
	  
	  this.convertToBase64(this.imageUrl)
		.then(base64Image => {
			if (!base64Image) {
			  console.error('图片转换失败');
			  return;
			}
			
			const base64Data = base64Image.replace(/^data:image\/\w+;base64,/, '');
			const encodedImage = encodeURIComponent(base64Data);
			
			uni.request({
			  url: `https://131egchhsfhds.cfc-execute.bj.baidubce.com/image`,
			  method: 'POST',
			  header: {
			    'Content-Type': 'application/x-www-form-urlencoded'
			  },
			  data: {
			    image: base64Data
			  },
			  success: (res) => {
			    console.log('API响应:', res.data);
			    if (res.data.error_code) {
			      console.error('API错误:', res.data.error_msg);
			      return;
			    }
			
			    if (res.data.result && res.data.result.length > 0) {
			      const result = res.data.result[0];
			      this.animalInfo = {
			        name: result.name,
			        score: result.score,
			        baike_info: result.baike_info || {}
			      };
			    } else {
			      console.error('未检测到动物信息');
			      this.animalInfo = null;
			    }
			  },
			  fail: (error) => {
			    console.error('API请求失败:', error);
			  }
			});
		})
      
    },

    convertToBase64(filePath) {
		
      return new Promise((resolve, reject) => {
			  fetch(filePath).then(r => r.blob())
				.then(blob => {
					
					const reader = new FileReader();
					reader.readAsDataURL(blob);
					reader.onload = () => resolve(reader.result);
					reader.onerror = (error) => reject(error);
				})
          });
    },
  }
};
</script>